package project.order.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kernel.util.Arith;
import kernel.util.StringUtils;
import kernel.web.BaseAction;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import project.order.Order;
import project.order.OrderService;
import project.order.OrderTemp;
import project.order.OrderTempService;
import project.order.weixi.SDKRuntimeException;
import project.order.weixi.WxPayHelper;
import project.order.work.WxOpenIdHelper;
import project.product.Brand;
import project.product.BrandService;
import project.product.Button;
import project.product.ButtonService;
import project.product.Cloth;
import project.product.ClothService;
import project.product.Stlye;
import project.product.StyleService;
import project.user.User;
import project.user.UserService;
import project.vip.po.Vip;
import project.vip.services.AdminVipService;
import project.vip.utils.KBProperties;

public class OrderAction extends BaseAction {
    private static final Log logger = LogFactory.getLog(OrderAction.class);

    /**	
        * Member Description
        */

    private static final long serialVersionUID = -2919817164903586450L;

    private boolean call;
    private String fd4sm;
    private boolean trade_in;

    private String stlye_id;
    
    private String btn_id;

    private String cloth_id;
    
    private String height;

    private String weight;

    private String size;
    
    private String size2;

    private String positive;

    private String back;

    private String text;

    private Cloth cloth;

    private Stlye stlye;
    
    private Button button;

    private Brand brand;

    private ClothService clothService;

    private StyleService styleService;
    
    private ButtonService buttonService;

    private BrandService brandService;

    private OrderService orderService;

    private OrderTempService orderTempService;
    private AdminVipService adminVipService;
    /**
	 * 成功下单后的order id
	 */
	private String fdOrderId;
    // 用户姓名
    private String name;

    // 手机号码
    private String phone;

    // 收货地址
    private String address;

    private String images1;

    private String images2;

    private String bizPackage;

    private String state;

    private String code;

    private String openid;

    private boolean binding;

    private UserService userService;

	private String fd4cs;
    
    private String redirect_url;
    private String brand_id;
    private Brand brandVip = null;
    public String userAuth() throws IOException {
    	 redirect_url = WxOpenIdHelper.getUserCodeUrl("userAuth");
    	 return "userAuth";
    }
    public String userAuthView() {
    	JSONObject userInfo = WxOpenIdHelper.getUserAuthInfo(code);
    	System.out.println("userInfo="+userInfo);
    	return "userAuthView";
    }
    public String view() {
        OrderTemp orderTemp = orderTempService.get(state);
        cloth = clothService.getCloth(orderTemp.getCloth());
        cloth_id = orderTemp.getCloth();
        call = orderTemp.getCall();
        trade_in = orderTemp.getTrade_in();
        stlye_id = orderTemp.getStlye();
        btn_id = orderTemp.getButton();
        height = orderTemp.getHeight();
        weight = orderTemp.getWeight();
        size = orderTemp.getSize();
        positive = orderTemp.getPositive();
        back = orderTemp.getBack();
        text = orderTemp.getText();
        images1 = orderTemp.getImages1();
        images2 = orderTemp.getImages2();
        size2 = orderTemp.getSize2();
        fd4sm = orderTemp.getFd4sm();
        name = orderTemp.getName();
        phone = orderTemp.getPhone();
        address = orderTemp.getAddress();
        brandVip = brandService.getBrand(brand_id);
        if (KBProperties.isTest) {
        	 openid = WxOpenIdHelper.getOpenId(code);
		}
       

//        User userInfo = userService.find(openid);
//        if (userInfo != null) {
//            name = userInfo.getName();
//            phone = userInfo.getPhone();
//            address = userInfo.getAddress();
//        }

        return "view";
    }
    /**
	 * 更新order
	 * @return
	 * @throws SDKRuntimeException
	 */
	public String updateOrder() throws SDKRuntimeException {

		HashMap<String, String> nativeObj = new HashMap<String, String>();
		Order o = orderService.getOrder(fdOrderId);
		o.setPayment(1);
        o.setFirmOrder("1");
		orderService.update(o);

		Vip vip = adminVipService.find(openid);
		if (vip != null) {
			
			if(vip.getGoldBt() > 0){
				vip.setGoldBt(vip.getGoldBt() - o.getFd4goldnum());//扣减金纽扣
				//判断是否选择上门券
				if(o.getFd4sm().equals("10")){//需要上门券
					vip.setSmTicket(vip.getSmTicket() - 1);
				}
				//判断是否选择衬衫券
				if(o.getFd4cs().equals("10")){
					vip.setCsTicket(vip.getCsTicket() - 1);
				}
				adminVipService.update(vip);
				nativeObj.put("code", "success");
				nativeObj.put("message", "下单成功!");
			}else{
				nativeObj.put("code", "fail");
				nativeObj.put("message", "金纽扣不足!");
			}
		}else{
			nativeObj.put("code", "fail");
			nativeObj.put("message", "vip查找失败!");
		}
		
		
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(JSONObject.fromObject(nativeObj).toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
	/**
	 * check order
	 * 符合条件：是会员，有金纽扣,单品不用上门券
	 * @return
	 * @throws SDKRuntimeException
	 */
	public String checkOrder() throws SDKRuntimeException {

		HashMap<String, String> nativeObj = new HashMap<String, String>();
		
		Vip vip = adminVipService.find(openid);

		nativeObj.put("code", "success");
		nativeObj.put("message", "可以下单!");
		if (vip != null) {
			if(vip.getGoldBt() > 0){//有金纽扣
				//判断是否需要购买上门券
				if(null != fd4sm && fd4sm.equals("10")){//需要上门券
					if(vip.getSmTicket() > 0){//有足够的上门券
						 //如果品牌可以消耗衬衫券则
					}else{
						//nativeObj.put("code", "fail");
						//nativeObj.put("message", "上门券不足!");
					}
				}
			}else{
				nativeObj.put("code", "fail");
				nativeObj.put("message", "金纽扣不足!");
			}
		}else{
			nativeObj.put("code", "fail");
			nativeObj.put("message", "找不到该vip!");
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(JSONObject.fromObject(nativeObj).toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
    public String pay() throws SDKRuntimeException {

       

            User user = userService.find(openid);
            if (user != null) {
                user.setAddress(address);
                user.setName(name);
                user.setPhone(phone);
                userService.update(user);
            }
            else {
                user = new User();
                user.setAddress(address);
                user.setName(name);
                user.setPhone(phone);
                user.setOpenId(openid);
                userService.save(user);
            }
     
            

        Order order = new Order();
        getBrand();
      //判断
		String message = "";
		String code = "success";
		
		Vip vip = adminVipService.find(openid);
		if (vip != null) {
			if(vip.getGoldBt() - brand.getFd4goldnum() >= 0){//有金纽扣
				//vip.setGoldBt(vip.getGoldBt() - brand.getFd4goldnum());//扣减金纽扣
				order.setFd4goldnum(brand.getFd4goldnum());//订单消耗金纽扣
				//判断是否选择上门券
				if(null != fd4sm && fd4sm.equals("10")){//需要上门券
					if(vip.getSmTicket() > 0){//有足够的上门券
						//vip.setSmTicket(vip.getSmTicket() - 1);
						order.setFd4sm("10");//订单消耗上门券
					}else{
						//code = "fail";
						//message = "上门券不足!";
						order.setFd4sm("00");//无上门券
					}
				}else{
					order.setFd4sm("00");//订单消耗上门券
				}
				//判断是否选择衬衫券
				if(null != fd4cs && fd4cs.equals("true")){//需要上门券
					if(vip.getCsTicket() > 0){
						//vip.setCsTicket(vip.getCsTicket() - 1);
						order.setPrice(brand.getBookPrice() - brand.getFdTypePrice());
						message = "系统自动使用衬衫券["+brand.getFdTypePrice()+"]抵扣!";
						order.setFd4cs("10");//订单消耗衬衫券
					}else{
						code = "fail";
						message = "衬衫券不足!";
					}
				}else{
					order.setFd4cs("00");//订单消耗衬衫券
					order.setPrice(brand.getBookPrice());
				}
				
			}else{
				code = "fail";
				message = "金纽扣不足!";
			}
		}else{
			code = "fail";
			message = "你不是会员!";
		}
		
		if(code.equals("fail")){
			HashMap<String, String> tempMap = new HashMap<String, String>();
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			try {
				tempMap.put("code", code);
				tempMap.put("message", message);
				out = response.getWriter();
				out.println(JSONObject.fromObject(tempMap).toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}else{
			order.setName(name);
	        order.setAddress(address);
	        order.setPhone(phone);
	        
	        order.setButton(brand.getId().toString());
	        order.setBrand(brand.getName());
	        order.setBrand_img(brand.getImg());
	        order.setSingle(brand.getSingle());

	        getCloth();
//	        System.out.println(cloth_id+"cloth="+cloth);
	        order.setCloth(cloth.getName());
	        order.setCloth_img(cloth.getImg());

	        getStlye();
	        order.setStlye(stlye.getName());
	        order.setStlye_img(stlye.getImg());
	        
//	        getButton();
//	        order.setButton(button.getName());
//	        order.setButton_img(button.getImg());

	        order.setCall(call);
	        order.setTrade_in(trade_in);

	        order.setHeight(height);
	        order.setWeight(weight);
	        order.setSize(size);
	        order.setPositive(positive);
	        order.setBack(back);
	        order.setText(text);
	        order.setPayment(0);
	        order.setImages1(images1);
	        order.setImages2(images2);
	        order.setOpenId(openid);
	        order.setSize2(size2);
	        order.setFirmOrder("0");
			order.setFd4gold("10");//设置金纽扣使用
			order.setFd4goldnum(1);//设置金纽扣数量1 为了区别是购买的卡会员而不是购买商城的商品
	        orderService.save(order);

	        WxPayHelper wxPayHelper = new WxPayHelper();

	        /**
	         * 商品描述
	         */
	        wxPayHelper.SetParameter("body", ""+ message+order.toString());
//	        wxPayHelper.SetParameter("body", "orderzhishan");
	        /**
	         * 订单号
	         */
	        wxPayHelper.SetParameter("out_trade_no", order.getId().toString());
	        /**
	         * 付款金额
	         */
	        wxPayHelper.SetParameter("total_fee", String.valueOf(Arith.mul(order.getPrice(), 100)).substring(0,String.valueOf(Arith.mul(order.getPrice(), 100)).indexOf(".")));
//	        wxPayHelper.SetParameter("total_fee", "1");

	        HttpServletRequest req = (HttpServletRequest) ServletActionContext.getRequest();
	        String visitorIp = req.getRemoteAddr();
	        wxPayHelper.SetParameter("spbill_create_ip", visitorIp);
	        wxPayHelper.SetParameter("openid", openid);

	        HashMap<String, String> tempMap = new HashMap<String, String>();
			tempMap = wxPayHelper.CreateBizPackageMap();
			//增加订单号回传
			tempMap.put("fdOrderId", order.getId().toString());
			tempMap.put("code", code);
			tempMap.put("message", message);
			
	        HttpServletResponse response = ServletActionContext.getResponse();
	        response.setContentType("application/json");
	        response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			try {
				out = response.getWriter();
				out.println(JSONObject.fromObject(tempMap).toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
        
		

    }

    public void paySuccess() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        InputStream inStream = null;
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        String result = null;
        try {
            inStream = request.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            result = new String(outSteam.toByteArray(), "utf-8");
        } catch (Exception e) {
            logger.error("paySuccess error:", e);
            writer(response, "FAIL");
        } finally {
            try {
                outSteam.close();
            } catch (IOException e) {
            }
            try {
                inStream.close();
            } catch (IOException e) {
            }
        }

        Map<Object, Object> map = null;
        try {
            map = XMLUtil.doXMLParse(result);
        } catch (Exception e) {
            logger.error("paySuccess error:", e);
            writer(response, "FAIL");
        }

        String out_trade_no = (String) map.get("out_trade_no");

        orderService.handle(out_trade_no);
        writer(response, "SUCCESS");

    }

    private void writer(HttpServletResponse response, String code) {
        try {
            response.getWriter().write(code);
        } catch (IOException e) {
            logger.error("paySuccess error:", e);
        }
    }

    public boolean isCall() {
        return call;
    }

    public void setCall(boolean call) {
        this.call = call;
    }

    public boolean isTrade_in() {
        return trade_in;
    }

    public void setTrade_in(boolean trade_in) {
        this.trade_in = trade_in;
    }

    public String getStlye_id() {
        return stlye_id;
    }

    public void setStlye_id(String stlye_id) {
        this.stlye_id = stlye_id;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getPositive() {
        return positive;
    }

    public void setPositive(String positive) {
        this.positive = positive;
    }

    public String getBack() {
        return back;
    }

    public void setBack(String back) {
        this.back = back;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Cloth getCloth() {
        if (cloth == null) {
//        	System.out.println("clothService="+clothService);
            cloth = clothService.getCloth(cloth_id);
        }
        return cloth;
    }

    public Stlye getStlye() {
        if (stlye == null) {
            stlye = styleService.getStlye(stlye_id);
        }
        return stlye;
    }
    
    public Button getButton() {
        if (button == null) {
        	button = buttonService.getButton(btn_id);
        }
        return button;
    }
    

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Brand getBrand() {
        if (brand == null) {
            stlye = styleService.getStlye(stlye_id);
            button = buttonService.getButton(btn_id);
            cloth = clothService.getCloth(cloth_id);
            if(null != cloth){
            	brand = brandService.getBrand(cloth.getBrand_id());
            }else{
            	brand = brandService.getBrand(stlye.getBrand_id());
            }
            
        }

        return brand;
    }

    public void setClothService(ClothService clothService) {
        this.clothService = clothService;
    }

    public void setStyleService(StyleService styleService) {
        this.styleService = styleService;
    }

    public void setBrandService(BrandService brandService) {
        this.brandService = brandService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public String getImages1() {
        return images1;
    }

    public void setImages1(String images1) {
        this.images1 = images1;
    }

    public String getImages2() {
        return images2;
    }

    public void setImages2(String images2) {
        this.images2 = images2;
    }

    public String getBizPackage() {
        return bizPackage;
    }

    public void setOrderTempService(OrderTempService orderTempService) {
        this.orderTempService = orderTempService;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public boolean isBinding() {
        return binding;
    }

    public void setBinding(boolean binding) {
        this.binding = binding;
    }

    public String getSize2() {
        return size2;
    }

    public void setSize2(String size2) {
        this.size2 = size2;
    }

	public String getBtn_id() {
		return btn_id;
	}

	public void setBtn_id(String btn_id) {
		this.btn_id = btn_id;
	}


	public void setButtonService(ButtonService buttonService) {
		this.buttonService = buttonService;
	}

	public String getRedirect_url() {
		return redirect_url;
	}

	public void setRedirect_url(String redirect_url) {
		this.redirect_url = redirect_url;
	}
	public String getCloth_id() {
		return cloth_id;
	}
	public void setCloth_id(String cloth_id) {
		this.cloth_id = cloth_id;
	}
	/**
	 * @return the fd4sm
	 */
	public String getFd4sm() {
		return fd4sm;
	}
	/**
	 * @param fd4sm the fd4sm to set
	 */
	public void setFd4sm(String fd4sm) {
		this.fd4sm = fd4sm;
	}
	/**
	 * @return the fdOrderId
	 */
	public String getFdOrderId() {
		return fdOrderId;
	}
	/**
	 * @param fdOrderId the fdOrderId to set
	 */
	public void setFdOrderId(String fdOrderId) {
		this.fdOrderId = fdOrderId;
	}
	/**
	 * @param adminVipService the adminVipService to set
	 */
	public void setAdminVipService(AdminVipService adminVipService) {
		this.adminVipService = adminVipService;
	}
	/**
	 * @return the brand_id
	 */
	public String getBrand_id() {
		return brand_id;
	}
	/**
	 * @param brand_id the brand_id to set
	 */
	public void setBrand_id(String brand_id) {
		this.brand_id = brand_id;
	}
	/**
	 * @return the brandVip
	 */
	public Brand getBrandVip() {
		return brandVip;
	}
	/**
	 * @param brandVip the brandVip to set
	 */
	public void setBrandVip(Brand brandVip) {
		this.brandVip = brandVip;
	}

}
